Memory leak with [NSMutableData appendData:]

Instruments reveals that the following simple code leaks memory on each delegate invoke:

- (void)start {
    [_urlSession dataTaskWithURL:_url];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [_data appendData:data];
}

I don't have any clue on this leak, it should not happen. What should I do to avoid this?

I'm not sure I follow your reasoning here.

In the first screenshot, the highlighted item is a 4MB memory block that was last resized in the delegate method, suggesting it's the memory block associated with your _data object reference. There's nothing to suggest that it's leaked there at all.

In the second screenshot, it looks like a leak of only 16 bytes was detected. That suggests it's the local data variable reference's memory, not _data and there's no evidence there that it's leaking every time.

I think in this scenario, the Leaks instrument isn't doing you any favors, because you have no insight into why it thinks this memory is being leaked. It'd probably be more productive to focus on the Allocations instrument (within the Allocations template), then use the "Mark Generation" button to isolate the allocations that remain after a specific download session:

https://developer.apple.com/documentation/xcode/gathering-information-about-memory-use/#Profile-your-app-using-the-Allocations-instrument

That should give you a clearer idea of which memory (if any) is actually being leaked.

Finally I have to re-invent the wheel to solve this mysterious memory leak which I cannot control without the wheel.

I am not sure if it is too bold to declare that NSData has serious problems with memory footprint, but...

After I devised my own memory management facility (a smart buffer class), the memory footprint drops drastically and stops growing continuously. This is observed for several days.

Memory leak with [NSMutableData appendData:]
 
 
Q